// 文件目录相关
const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec
const join = require('path').join
const request = require('request')

const fileDir = {
  fs: fs,
  disk: [],
  deskTop: '',
  childProcess: exec
}

export function initFileDir () {
  const commandDisk = exec('wmic logicaldisk get name', (error, stdout, stderr) => {
    if (error) {
      return
    }
    stdout = stdout.split('\n')
    for (var i = 1, len = stdout.length; i < len; i++) {
      if (stdout[i]) {
        stdout[i] = stdout[i].replace(/^\s+|\s+$/g, '')
        fileDir.disk.push(stdout[i])
      }
    }
  })
  const commandDeskTop = exec('echo %UserProfile%\\Desktop', (error, stdout, stderr) => {
    if (error) {
      return false
    }
    fileDir.deskTop = stdout.split('\n')[0].replace(/^\s+|\s+$/g, '')
  })
  commandDisk.stdin.end()
  commandDeskTop.stdin.end()
}

let localId = 0
// 获取本地根节点(桌面、C、D、E盘)目录列表
export function getLocalFolderList () {
  const roots = []
  if (fileDir.fs && JSON.stringify(fileDir.fs) !== '{}') {
    if (typeof fileDir.deskTop !== 'undefined') {
      const deskTop = fileDir.deskTop.split('\\').join('/')
      if (deskTop) {
        roots.push({
          id: localId,
          desk: true,
          _name: 'Desktop',
          path: deskTop + '/',
          label: '桌面',
          icon: 'iconfont icontubiao-30',
          iconColor: 'primary',
          children: [],
          lazy: true,
          source: 'local'
        })
        localId++
      }
    }
    for (let d = 0, len = fileDir.disk.length; d < len; d++) {
      if (fileDir.disk[d]) {
        roots.push({
          id: localId,
          disk: true,
          _name: fileDir.disk[d],
          path: fileDir.disk[d] + '/',
          label: fileDir.disk[d] + '盘',
          icon: 'img:statics/svg/file-icon.svg',
          children: [],
          lazy: true,
          source: 'local'
        })
        localId++
      }
    }
  }
  return roots
}
// 获取文件夹下的子文件和子文件夹
export function getFolderChildList (node) {
  let dirs = []
  let newDirs = []
  let newFiles = []
  let nodes = []
  try {
    dirs = fileDir.fs.readdirSync(node.path)
  } catch (e) {
    if (node.desk) {
      node.path = node.path.replace('Desktop', '桌面')
      dirs = fileDir.fs.readdirSync(node.path)
    }
  }
  for (let i = 0, len = dirs.length; i < len; i++) {
    try {
      let stats = fileDir.fs.statSync(node.path + dirs[i])
      if (stats.isDirectory()) {
        newDirs.push({
          id: localId,
          size: stats.size,
          timestamp: new Date(stats.mtime).getTime(),
          label: dirs[i],
          path: node.path + dirs[i] + '/',
          icon: 'img:statics/svg/file-icon.svg',
          lazy: true,
          isFile: stats.isFile(),
          source: 'local',
          children: []
        })
      } else {
        // 文件后缀名
        let extname = path.extname(dirs[i]).substr(1)
        let type = path.extname(dirs[i]).length > 0 ? getFiletype(extname) : 'other'
        newFiles.push({
          id: localId,
          size: stats.size,
          timestamp: new Date(stats.mtime).getTime(),
          label: dirs[i],
          path: node.path + dirs[i],
          icon: 'img:statics/svg/' + type + '.svg',
          isFile: stats.isFile(),
          lazy: false,
          source: 'local',
          type
        })
      }
      localId++
    } catch (e) {
      console.warn(e)
    }
  }
  nodes = [].concat(newDirs, newFiles)
  console.log(nodes)
  return { dirs: newDirs, nodes }
}
function getFiletype (extname) {
  let word = ['doc', 'docx', 'rtf']
  let excel = ['xlsx', 'xls', 'csv']
  let ppt = ['ppt', 'pptx', 'pps', 'pot', 'ppa']
  let pdf = ['pdf']
  let link = ['lnk']
  let video = ['avi', 'mov', 'rm', 'ram', '3gp', 'flv', 'mpg', 'mpeg', 'rmvb', 'mp4', 'm2v', 'mkv', 'mov', 'swf']
  let audio = ['mp3', 'mp2', 'mp1', 'wav', 'wmv', 'wma', 'amr', 'mid', 'cda', 'vqf']
  let img = ['png', 'jpg', 'jpeg', 'bmp', 'rle', 'dib', 'gif', 'psd', 'pdd', 'ai', 'pic', 'did', 'tif', 'tiff', 'tga', 'ico', 'raw']
  // 压缩包
  let compress = ['rar', 'zip', 'arj', 'z']
  if (word.indexOf(extname) > -1) {
    return 'word'
  }
  if (excel.indexOf(extname) > -1) {
    return 'excel'
  }
  if (ppt.indexOf(extname) > -1) {
    return 'ppt'
  }
  if (pdf.indexOf(extname) > -1) {
    return 'pdf'
  }
  if (link.indexOf(extname) > -1) {
    return 'link'
  }
  if (video.indexOf(extname) > -1) {
    return 'video'
  }
  if (audio.indexOf(extname) > -1) {
    return 'audio'
  }
  if (img.indexOf(extname) > -1) {
    return 'img'
  }
  if (compress.indexOf(extname) > -1) {
    return 'compress'
  }
  return 'other'
}
// 重命名文件
export function setNewName (path, newName, func) {
  let paths = path.split('/')
  paths = paths.slice(0, paths.length - 1)
  const newPath = paths.join('/')
  fs.rename(path, newPath + '/' + newName, func)
}
// 删除文件夹
export function rmDir (path, func) {
  fs.rmdir(path, func)
}
// 删除文件
export function rmFile (path, func) {
  fs.unlink(path, func)
}
// 创建文件夹
export function newDir (path, func) {
  fs.mkdir(path, { recursive: true }, func)
}

// 读取文件
export function readFile (path, errFun, successFun) {
  let reader = new FileReader()
  reader.onload = (evt) => {
    successFun(evt.target.result, 'utf-8')
    console.log(evt.target.result)
  }
  reader.onerror = err => {
    errFun(err)
  }
  reader.readAsText(path)
}

// 编辑文件
export function editFile (path, code, func) {
  fs.writeFile(path, code, func)
}
// 下载写入文件
export function writeFile (dataUrl, file, func) {
  let info = {
    progress: 0,
    state: 'download'
  }
  const fileSaver = require('file-saver')
  fileSaver.saveAs(dataUrl, `${file._name || file.label}`)
  setTimeout(() => {
    info.progress = 1
    info.state = 'success'
    func(info)
  })
}
// 删除目录，一级下面的子项
export function deleteDirectory (dirPath) {
  return new Promise((resolve, reject) => {
    fs.access(dirPath, err => {
      if (err) reject(err)
      fs.readdir(dirPath, (err, files) => {
        if (err) reject(err)
        Promise.all(files.map(file => {
          return deleteFile(dirPath, file)
        })).then(() => {
          fs.rmdir(dirPath, err => {
            if (err) reject(err)
            resolve()
          })
        }).catch(reject)
      })
    })
  })
}

function deleteFile (dirPath, file) {
  return new Promise((resolve, reject) => {
    let filePath = path.join(dirPath, file)
    fs.stat(filePath, (err, stats) => {
      if (err) reject(err)
      if (stats.isFile()) {
        fs.unlink(filePath, err => {
          if (err) reject(err)
          resolve()
        })
      } else {
        // 返回deleteDirectory在all中递归调用
        resolve(deleteDirectory(filePath))
      }
    })
  })
}

// 获取实际的文件列表，有文件夹的获取文件夹里面的文件
export function getFilesForDict (Files) {
  let fileList = [], flag = true
  // 查询文件
  function finder (path) {
    if (!flag) {
      return
    }
    let files = fs.readdirSync(path)
    if (!files.length) {
      fileList.push([path, ''])
    } else {
      for (let i = 0, len = files.length; i < len; i++) {
        try {
          let fPath = join(path, files[i])
          let stats = fs.statSync(fPath)
          if (stats.isDirectory()) {
            finder(fPath + '/')
          }
          if (stats.isFile()) {
            fileList.push([fPath, files[i]])
            if (fileList.length > 50) {
              flag = false
              break
            }
          }
        } catch (e) {}
      }
    }
  }
  for (let p = 0, pLen = Files.length; p < pLen; p++) {
    if (Files[p].isFile) {
      fileList.push([Files[p].path, Files[p].label])
      if (fileList.length > 50) {
        return false
      }
      continue
    }
    finder(Files[p].path)
  }
  return flag ? fileList : flag
}

// 读取文件信息
export function getFileStats (send, acceptPath, putFun, accept) {
  let arr = []
  // 创建一个readStream对象，根据文件起始位置和结束位置读取固定的分片
  let readStream = fs.createReadStream(send[0])
  // on data读取数据
  readStream.on('data', (data) => {
    arr.push(data)
  })
  // on end在该分片读取完成时触发
  readStream.on('end', () => {
    // 这里服务端只接受blob对象，需要把原始的数据流转成blob对象，这块为了配合后端才转
    let blob = new Blob(arr)
    putFun(blob, send, acceptPath, accept)
  })
}

// 流式写入文件
export async function createWriteStream (cloudPath, localPath) {
  try {
    console.log(this.client)
    let result = await this.client.getStream(cloudPath)
    console.log(result)
    let writeStream = createWriteStream(localPath)
    result.stream.pipe(writeStream)
  } catch (e) {
    console.log(e)
  }
  // let writeStream = fs.createWriteStream('local-file')
  // return writeStream
}

// 跳转到文件位置
export function goPosition (url) {
  let command
  switch (process.platform) {
    case 'darwin':
      // macOS
      command = `open -R "${url}"`
      break
    case 'win32':
      // Windows
      command = `explorer.exe /select,"${url}"`
      break
    default:
      return
  }

  exec(command)
  // exec(`explorer.exe /select,"${url}"`)
}

// 判断是否存在
export function fileExist (url) {
  return fs.existsSync(url)
}

export function downloadFile (sendPath, acceptPath, callback) {
  let info = {
    sendPath,
    acceptPath,
    size: 0,
    progress: 0,
    receiveBytes: 0,
    state: 'download'
  }
  const req = request({
    method: 'GET',
    uri: sendPath
  })
  const out = fs.createWriteStream(acceptPath)
  req.pipe(out)
  req.on('response', data => {
    info.size = parseInt(data.headers['content-length'], 10)
    callback(info)
  })
  req.on('data', (chunk) => {
    info.receiveBytes += chunk.length
    callback(info)
  })
  req.on('end', () => {
    info.receiveBytes = info.size
    info.progress = 1
    info.state = 'success'
    callback(info)
  })
}

// 根据本地路径，获取文件信息
export function getFileInfo (path) {
  return fs.statSync(path)
}
